#include "timer_x.h"
#include "freertos/FreeRTOS.h"

gptimer_handle_t gptimer = NULL;

// timer_init_t m_timer_inst;
// typedef struct
// {
//     uint64_t event_count;
// } example_queue_element_t;

// // uint16_t c = 0;
// static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
// {
//     BaseType_t high_task_awoken = pdFALSE;
//     // QueueHandle_t queue = (QueueHandle_t)user_ctx;
//     // // Retrieve the count value from event data
//     // example_queue_element_t ele = {
//     //     .event_count = edata->count_value};
//     // // Optional: send the event data to other task by OS queue
//     // // Don't introduce complex logics in callbacks
//     // // Suggest dealing with event data in the main loop, instead of in this callback
//     // xQueueSendFromISR(queue, &ele, &high_task_awoken);
//     // return whether we need to yield at the end of ISR

//     // xTaskNotifyGive(xTask1);
//     m_timer_inst.handler();

//     // c++;
//     // if (c<5){
//     // }

//     // if (c>20){
//     //     xTaskNotifyGive(xTask1);
//     // }

//     return high_task_awoken == pdTRUE;
// }

void timer_x_init(const gptimer_event_callbacks_t *cbs)
{
    // m_timer_inst.handler = timer_init.handler;
    gptimer_config_t timer_config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        // .resolution_hz = 1 * 1000 * 1000, // 1MHz, 1 tick = 1us
        // .resolution_hz = 1 * 1000 * 10, // 10KHz, 1 tick = 100us
        // .resolution_hz = 1 * 1000 , // 1KHz, 1 tick = 1ms
        .resolution_hz = 1 * 1000* 200 , // 200KHz, 1 tick = 5us
    };

    ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer));
    gptimer_alarm_config_t alarm_config = {
        .reload_count = 0,                  // counter will reload with 0 on alarm event
        // .alarm_count = 50,                
        // .alarm_count = 5,                // period = 500us 
        .alarm_count = 125,                // period = 625us 
        .flags.auto_reload_on_alarm = true, // enable auto-reload
    };
    ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));

    // gptimer_event_callbacks_t cbs = {
    //     .on_alarm = example_timer_on_alarm_cb, // register user callback
    // };
    ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, cbs, NULL));
    ESP_ERROR_CHECK(gptimer_enable(gptimer));        
    ESP_ERROR_CHECK(gptimer_start(gptimer));
}

